package com.ayitubie.refuelweb.config.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e) {
        log.error("系统错误 {}",e);
        return ResultData.fail(500, e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultData<String> paramsException(MethodArgumentNotValidException e) throws Exception{
        log.error("参数错误 {}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String , String> map = new HashMap<>();
        ObjectMapper om = new ObjectMapper();
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach( (item) -> {
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put( field , message );
            });
        }
        return ResultData.fail(400, om.writeValueAsString(map));
    }
}
